package com.kobeliu.api.mq;


import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * rabbitMQ工具类
 */
@Configuration
@Slf4j
public class MessageConfig {

    //定义交换机
    public static final String EXCHANGE_MSG = "exchange_chat_msg";
    //定义队列
    public static final String QUEUE_MSG = "queue_chat_msg";
    //定义路由key
    public static final String SAVE_MSG_ROUTING_KEY = "imooc.chat.msg.save.do";

    //创建交换机
    @Bean(EXCHANGE_MSG)
    public Exchange exchange(){
        return ExchangeBuilder
                .topicExchange(EXCHANGE_MSG)
                .durable(true)
                .build();
    }

    //创建队列
    @Bean(QUEUE_MSG)
    public Queue queue(){
        return QueueBuilder
                .durable(QUEUE_MSG)
                .build();
    }

    //创建绑定关系
    @Bean
    public Binding chatMsgBinding(@Qualifier(EXCHANGE_MSG) Exchange exchange, @Qualifier(QUEUE_MSG) Queue queue){
        return BindingBuilder.bind(queue)
                            .to(exchange)
                            .with("imooc.chat.msg.save.*")
                            .noargs();
    }

    @Bean
    public RabbitTemplate.ConfirmCallback chatConfirmCallback() {
        RabbitTemplate.ConfirmCallback chatConfirmCallback = new RabbitTemplate.ConfirmCallback() {
            /**
             * 回调函数
             *
             * @param correlationData 传入的数据
             * @param ack             true为成功 false为失败
             * @param msg             若成功，传回null,若失败，传回原因
             */
            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String msg) {

                log.info("传入交换机的消息为:{}", correlationData);
                log.info("传入是否成功:{}", ack);
                log.info("若传入失败，原因是:{}", msg);

            }

        };
        return chatConfirmCallback;
    }

}
